use memmap2::MmapOptions;
use std::fs::OpenOptions;
use std::io;
use std::thread;
use std::time::Duration;

fn main() -> io::Result<()> {
    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .open("temp")?;

    file.set_len(4096)?; // Ensure the file is of the correct size

    let mut mmap = unsafe { MmapOptions::new().len(4096).map_mut(&file)? };

    loop {
        {
            let slice = &mut mmap[1024..(1024 + "haha, I'm fine".len())];
            slice.copy_from_slice(b"haha, I'm fine");
        } // Ensures flush happens before sleep

        println!("message written to the shared memory~");
        thread::sleep(Duration::from_secs(2));
    }

    // The munmap operation is handled automatically when mmap goes out of scope.
}
